package com.example.dangerouscargodriver.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.baiju.bjpopupwindow.view.BottomDialog;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.ImageUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;

public class RefuseCancelOrderActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "RefuseCancelOrderActivity";
    //相册请求码
    private static final int ALBUM_REQUEST_CODE = 1;
    //相机请求码
    private static final int CAMERA_REQUEST_CODE = 2;

    private static final int ACTION_PROVE_ONE = 0;
    private static final int ACTION_PROVE_TWO = 1;

    private static final int SELECT_PROVE_ONE = 0;
    private static final int SELECT_PROVE_TWO = 1;

    private ActionBar mActionBar = null;

    private String mOrderId = null;

    private RelativeLayout mProveOneLayout = null;
    private LinearLayout mProveOneImageLayout = null;
    private ImageView mProveOneIv = null;
    private ImageView mProveOneIvLoading = null;
    private boolean mProveOneIvLoaded = false;

    private RelativeLayout mProveTwoLayout = null;
    private LinearLayout mProveTwoImageLayout = null;
    private ImageView mProveTwoIv = null;
    private ImageView mProveTwoIvLoading = null;
    private boolean mProveTwoIvLoaded = false;

    private BottomDialog mBottomDialog = null;
    private HashMap<String, String> mSelectPicture = null;

    //调用照相机返回图片文件
    private File mTempFile;

    private int mSelectType = SELECT_PROVE_ONE;

    private CheckBox mYes = null;
    private CheckBox mNo = null;

    private LinearLayout mLayoutReward = null;
    private EditText mRewardNum = null;
    private EditText mReason = null;

    private Button mCommit = null;
    private TextView mWordNum = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(RefuseCancelOrderActivity.class);
        setContentView(R.layout.activity_refuse_cancel_order);

        mOrderId = getIntent().getStringExtra("id");

        mProveOneLayout = findViewById(R.id.iv_prove_one_selector);
        mProveOneImageLayout = findViewById(R.id.layout_one_img);
        mProveOneIv = findViewById(R.id.iv_prove_one);
        mProveOneIvLoading = findViewById(R.id.iv_prove_one_loading);
        mProveOneLayout.setOnClickListener(this);
        mProveOneImageLayout.setOnClickListener(this);

        mProveTwoLayout = findViewById(R.id.iv_prove_two_selector);
        mProveTwoImageLayout = findViewById(R.id.layout_two_img);
        mProveTwoIv = findViewById(R.id.iv_prove_two);
        mProveTwoIvLoading = findViewById(R.id.iv_prove_two_loading);
        mProveTwoLayout.setOnClickListener(this);
        mProveTwoImageLayout.setOnClickListener(this);

        mSelectPicture = new HashMap<>();
        mBottomDialog = new BottomDialog();
        mBottomDialog.setOnItemClickListener(new BottomDialog.OnItemClickListener() {
            @Override
            public void onCamera() {
                getPicFromCamera();
            }

            @Override
            public void onAlbum() {
                getPicFromAlbum();
            }

            @Override
            public void onCancel() {

            }
        });

        mLayoutReward = findViewById(R.id.layout_reward);
        mRewardNum = findViewById(R.id.ed_reward_num);
        mWordNum = findViewById(R.id.tv_word_num);
        mReason = findViewById(R.id.ed_refuse_reason);
        mReason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mWordNum.setText(mReason.getText().length() + "/200");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mYes = findViewById(R.id.ck_yes);
        mYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mNo.setChecked(false);
                    mLayoutReward.setVisibility(View.VISIBLE);
                }
            }
        });
        mNo = findViewById(R.id.ck_no);
        mNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mYes.setChecked(false);
                    mLayoutReward.setVisibility(View.GONE);
                }
            }
        });

        mCommit = findViewById(R.id.btn_action_commit);
        mCommit.setOnClickListener(this);

        mActionBar = findViewById(R.id.actionBarRefuseCancelOrder);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private boolean checkUserInput(){
        if(!mYes.isChecked() && !mNo.isChecked()){
            return false;
        }

        if(mYes.isChecked() && mRewardNum.getText().toString().equals("")){
            return false;
        }

        if(mReason.getText().toString().equals("")){
            return false;
        }

        if(!mProveOneIvLoaded || !mProveTwoIvLoaded){
            return false;
        }

        return true;
    }

    private void executeTransportingCancelOrderRefuse(){
        if(mOrderId != null) {
            HashMap<String, String> header = new HashMap<String, String>();
            header.put("token", AuthController.Instance().getToken());

            JSONObject param = new JSONObject();
            try {
                param.put("type", 3);
                param.put("handling_reason", mReason.getText().toString());
                param.put("is_agree", "0");
                JSONObject refuse_info = new JSONObject();
                if(mYes.isChecked()) {
                    refuse_info.put("need_compensation", 1);
                    refuse_info.put("compensation", mRewardNum.getText().toString());
                }
                else{
                    refuse_info.put("need_compensation", 0);
                    refuse_info.put("compensation", 0);
                }
                refuse_info.put("reason", mReason.getText().toString());
                ArrayList<String> arrayList = new ArrayList<>();
                arrayList.add(mSelectPicture.get("proveOne"));
                arrayList.add(mSelectPicture.get("proveTwo"));
                refuse_info.put("prove", arrayList);
                param.put("refuse_info", refuse_info);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            sendHttpJsonRequest(
                    IHttpRequest.RequestMethod.PUT_METHOD,
                    RemoteAPI.REQUEST_V2_USER_SR_ORDER + "/" + mOrderId,
                    header,
                    param,
                    RemoteAPICmd.REQUEST_V2_USER_SR_ORDER_TRANSPORTING_CANCEL_REFUSE);
        }
        else{

        }
    }

    @SuppressLint("LongLogTag")
    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_ONE) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mProveOneIvLoading);
                    mProveOneIvLoaded = true;
                    if(mSelectPicture.containsKey("proveOne")){
                        mSelectPicture.remove("proveOne");
                    }
                    mProveOneImageLayout.setVisibility(View.GONE);
                    mProveOneIv.setVisibility(View.VISIBLE);
                    mSelectPicture.put("proveOne", res.getJSONObject("data").getString("url"));
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_TWO) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    stopAnimation(mProveTwoIvLoading);
                    mProveTwoIvLoaded = true;
                    if(mSelectPicture.containsKey("proveTwo")){
                        mSelectPicture.remove("proveTwo");
                    }
                    mSelectPicture.put("proveTwo", res.getJSONObject("data").getString("url"));
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR_ORDER_TRANSPORTING_CANCEL_REFUSE){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                ToastUtils.showLongToast(this, res.getString("message"));
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    finish();
                }
                else{

                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.iv_prove_one_selector || v.getId() == R.id.layout_one_img){
            mSelectType = SELECT_PROVE_ONE;
            mBottomDialog.showDialog(this);
        }
        else if(v.getId() == R.id.iv_prove_two_selector || v.getId() == R.id.layout_two_img){
            mSelectType = SELECT_PROVE_TWO;
            mBottomDialog.showDialog(this);
        }
        else if(v.getId() == R.id.btn_action_commit){
            if(checkUserInput()) {
                executeTransportingCancelOrderRefuse();
            }
            else{
                ToastUtils.showLongToast(this, "请填写完整拒单信息");
            }
        }
        else{

        }
    }

    /**
     * 从相册获取图片
     */
    private void getPicFromAlbum() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
    }

    private void getPicFromCamera(){
        mTempFile = new File(Environment.getExternalStorageDirectory() +
                File.separator + "vsiji" + File.separator
                + "Pictures", System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this,
                    "com.example.dangerouscargodriver.fileprovider",
                    mTempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        }
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void pushFileToRemote(String file, int action){
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());
        HashMap<String, String> param = new HashMap<>();
        param.put("water", "1");

        sendHttpMultipartRequest(RemoteAPI.REQUEST_UPLOAD_FILE,
                header,
                param,
                file,
                action);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                Log.d(TAG,String.valueOf(resultCode));
                if (resultCode == RESULT_OK) {
                    Bitmap bitmap = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(this,
                                "com.example.dangerouscargodriver.fileprovider",
                                mTempFile);
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(mTempFile);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        bitmap = BitmapFactory.decodeStream(fis);
                        bitmap = ImageUtils.extractMiniThumb(bitmap, 232, 155);
                    }
                    else {
                        bitmap = BitmapFactory.decodeFile(mTempFile.getPath());
                    }
                    if(mSelectType == SELECT_PROVE_ONE) {
                        mProveOneIv.setImageBitmap(bitmap);
                        mProveOneIv.setVisibility(View.VISIBLE);
                        mProveOneImageLayout.setVisibility(View.GONE);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_ONE);
                        startAnimation(mProveOneIvLoading);
                    }
                    else if(mSelectType == SELECT_PROVE_TWO){
                        mProveTwoIv.setImageBitmap(bitmap);
                        mProveTwoIv.setVisibility(View.VISIBLE);
                        mProveTwoImageLayout.setVisibility(View.GONE);
                        pushFileToRemote(mTempFile.getPath(),
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_TWO);
                        startAnimation(mProveTwoIvLoading);
                    }
                    else{

                    }
                }
                break;
            case ALBUM_REQUEST_CODE:    //调用相册后返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    String file = ImageUtils.getRealPathFromURI(uri, this);
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    bitmap = ImageUtils.extractMiniThumb(bitmap, 320, 160);
                    if(mSelectType == SELECT_PROVE_ONE) {
                        mProveOneIv.setImageBitmap(bitmap);
                        mProveOneIv.setVisibility(View.VISIBLE);
                        mProveOneImageLayout.setVisibility(View.GONE);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_ONE);
                        startAnimation(mProveOneIvLoading);
                    }
                    else if(mSelectType == SELECT_PROVE_TWO){
                        mProveTwoIv.setImageBitmap(bitmap);
                        mProveTwoIv.setVisibility(View.VISIBLE);
                        mProveTwoImageLayout.setVisibility(View.GONE);
                        pushFileToRemote(file,
                                RemoteAPICmd.REQUEST_UPLOAD_FILE + ACTION_PROVE_TWO);
                        startAnimation(mProveTwoIvLoading);
                    }
                    else{

                    }
                }
                break;
            default:
                break;
        }
    }

    private void startAnimation(ImageView imageView){
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);

        Animation rotateAnimation = AnimationUtils.loadAnimation(getBaseContext(),
                R.anim.anim_circle_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();
        rotateAnimation.setInterpolator(interpolator);
        imageView.setImageResource(R.drawable.ic_uploading);
        imageView.startAnimation(rotateAnimation);
        imageView.setVisibility(View.VISIBLE);
    }

    private void stopAnimation(ImageView imageView){
        imageView.clearAnimation();
        //imageView.setImageResource(R.drawable.ic_upload_done);
        imageView.setVisibility(View.INVISIBLE);
    }
}